﻿using Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;

namespace DAL
{
    public class SysMenuInfoDAL : BaseDAL
    {
        #region 加载菜单图片
        /// <summary>
        /// 加载用户头像
        /// </summary>
        /// <returns></returns>
        public bool DownMenuIcon()
        {
            Action<object> downIcon = (icon) =>
            {
                if (!string.IsNullOrWhiteSpace(icon as string))
                {
                    DownFileByRelativePath(icon.ToString());
                }
            };

            Action<object> errHander = (state) =>
            {
                Log.errorlog(new Exception("用户编号为“" + state + "”的头像下载失败！"));
            };

            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                int pageIdx = 1, pageSize = 100, headNums = 0;
                do
                {
                    var heads = conn.Query<dynamic>(" select top " + (pageIdx * pageSize) + "  ID,Icon  from SysMenuInfo where ID not in(select top " + ((pageIdx - 1) * pageSize) + " ID from SysMenuInfo order by ID asc) order by ID asc  ").ToList();
                    headNums = heads.Count();
                    pageIdx++;

                    heads.ForEach(item =>
                    {
                        FunHelper.TryAsync(downIcon, item.Head, null, null, errHander, item.ID);
                    });

                } while (headNums >= pageSize);
                conn.Close();
            }
            return false;
        }
        #endregion

        #region 头像下载
        /// <summary>
        /// 头像下载
        /// </summary>
        /// <param name="resource"></param>
        void DownFileByRelativePath(string icon)
        {
            try
            {
                icon = "/" + icon.Replace("\\", "/").Trim('/');
                if (string.IsNullOrWhiteSpace(icon) || !icon.IsFilePath())
                    return;
                FileDown<string> fd = new FileDown<string>(ConfigHelper.GetConfigString("RemoteUrl").TrimEnd('/') + "/" + icon.TrimStart('/'), ConfigHelper.GetConfigString("SourceDir"), 10);
                fd.Data = icon;
                fd.CallBack = (string _head) =>
                {

                };
                fd.Start();
            }
            catch (Exception ex)
            {
                Log.errorlog(ex);
            }
        }
        #endregion
    }
}
